package com.newy.web.sys;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newy.core.BaseController;
import com.newy.core.util.Converter;
import com.newy.domain.sys.Department;
import com.newy.domain.sys.Menu;
import com.newy.domain.sys.Role;
import com.newy.domain.sys.User;
import com.newy.service.sys.RoleService;
import com.newy.service.sys.UtilService;

/**
 * 角色管理控制器类
 * @author linzongxue
 * @create_date 2012-1-7
 */
@Controller
@RequestMapping("sys/role")
public class RoleController extends BaseController {
	@Resource private RoleService roleSvc;
	@Resource private UtilService utilSvc;

	@RequestMapping("save") @ResponseBody
	public Object save(Role role){
		roleSvc.save(role);
		return role;
	}
	
	@RequestMapping("delete") @ResponseBody
	public void delete(Long[] ids){
		roleSvc.delete(ids);
	}
	
	@RequestMapping("get") @ResponseBody
	public Object get(Long id){
		return roleSvc.get(id);
	}
	
	@RequestMapping("list") @ResponseBody
	public Object list(){
		return roleSvc.list();
	}
	
	@RequestMapping("addUsersToRole") @ResponseBody
	public void addUsersToRole(Long roleId, Long[] userIds){
		roleSvc.addUsersToRole(roleId, userIds);
	}
	
	@RequestMapping("removeUsersFromRole") @ResponseBody
	public void removeUsersFromRole(Long roleId, Long[] userIds){
		roleSvc.removeUsersFromRole(roleId, userIds);
	}

	/**
	 * 保存角色与菜单的关联
	 * @param roleId 指定的角色ID
	 * @param addMenuIds 要添加关联的菜单ID
	 * @param removeMenuIds 要删除关联的菜单ID
	 */
	@RequestMapping("saveMenusOfRole") @ResponseBody
	public void saveMenusOfRole(Long roleId, Long[] addMenuIds, Long[] removeMenuIds){
		roleSvc.addMenusToRole(roleId, addMenuIds);
		roleSvc.removeMenusFromRole(roleId, removeMenuIds);
	}

	@RequestMapping("getUsersOfRole") @ResponseBody
	public Object getUsersOfRole(Long roleId){
		List<User> users =  roleSvc.getUsersOfRole(roleId);
		return new Converter()
			.addField("departName", "departId", Department.class, "name")
			.removeField("password")
			.toListOfMap(users);
	}

	@RequestMapping("getMenusOfRole") @ResponseBody
	public Object getMenusOfRole(Long roleId){
		List<Menu> menus = roleSvc.getMenusOfRole(roleId);
		return new Converter().addField("idPath", new Converter.Convert<Menu>() {
			public Object to(Menu src){
				return utilSvc.getEntityAttrPath(src.getId(), "id", "parentId", src.getClass().getName());
			}
		}).toListOfMap(menus);
	}
}
